from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from apps.schemas.schemas import AnnouncementRequest, AnnouncementCreateRequest
from apps.services.announcements import get_all_announcements, update_announcement, add_announcement, delete_announcement

announcements = APIRouter()


@announcements.get("/msg")
async def get_all(page: int = 1, pagesize: int = 10):
    try:
        total, announcement_data = await get_all_announcements(page, pagesize)
        if total and announcement_data:
            return {"status": 200, "message": "success", "data": {"list": announcement_data, "total": total}}
        else:
            return {"status": 404, "message": "No announcements found"}
    except Exception as e:
        return {"status": 500, "message": f"Error retrieving announcements: {str(e)}"}


@announcements.put("/update")
async def update_(data: AnnouncementRequest):
    try:
        result = await update_announcement(data)
        if result:
            return {"status": 200, "message": "Announcement updated successfully"}
        else:
            return {"status": 404, "message": "Announcement not found"}
    except Exception as e:
        return {"status": 500, "message": f"Error updating announcement: {str(e)}"}


@announcements.post("/add")
async def add_(data: AnnouncementCreateRequest):
    try:
        result = await add_announcement(data)
        if result:
            return {"status": 200, "message": "Announcement created successfully"}
        else:
            return {"status": 500, "message": "Failed to create announcement"}
    except Exception as e:
        return {"status": 500, "message": f"Error creating announcement: {str(e)}"}


@announcements.delete("/delete")
async def delete_(data: AnnouncementRequest):
    try:
        result = await delete_announcement(data.announcement_id)
        if result:
            return {"status": 200, "message": "Announcement deleted successfully"}
        else:
            return {"status": 404, "message": "Announcement not found"}
    except Exception as e:
        return {"status": 500, "message": f"Error deleting announcement: {str(e)}"}
